package user

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

/*//
查找单个
*/

func FindOneUser(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) (*User, error) {
	result := new(User)
	err := result.GetCollection().FindOne(ctx, filter, opts...).Decode(result)
	if err != nil {
		return nil, err
	}
	return result, err
}

func decodeUserCursor(ctx context.Context, cursor *mongo.Cursor) (UserList *[]User, err error) {
	list := make([]User, 0)
	err = cursor.All(ctx, UserList)
	if err != nil {
		return nil, err
	}
	return &list, err
}

func QueryManyUser(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (result *[]User, err error) {
	cursor, err := (&User{}).GetCollection().Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}
	result, err = decodeUserCursor(ctx, cursor)
	return result, err
}

// FindLastOne /* 查找单个 */
func (u *User) FindLastOne(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) error {
	_opt := make([]*options.FindOneOptions, 0)
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	_opt = append(_opt, options.FindOne().SetSort(bson.D{{"_id", -1}}))
	return u.GetCollection().FindOne(ctx, *filter, _opt...).Decode(u)
}

func (u *User) FindByID(ctx context.Context, id any, opts ...*options.FindOneOptions) error {
	return u.FindLastOne(ctx, &bson.D{{"_id", id}}, opts...)
}

func (u *User) FindByLoginName(ctx context.Context, name *string, opts ...*options.FindOneOptions) error {
	err := u.FindLastOne(ctx, &bson.D{
		u.ConditionUserLoginName(name),
	})
	return err
}

/*//
查找多个
*/

type ManyUsers []User

// FindMany /* 查找d多个 */
func (inst *ManyUsers) FindMany(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	_opt := make([]*options.FindOptions, 0)
	_opt = append(_opt, options.Find().SetSort(bson.D{{"_id", -1}}))
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	cursor, err := (&User{}).GetCollection().Find(ctx, *filter, _opt...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, inst)
}
